import Bmob from "hydrogen-js-sdk";
import { config } from "../config/index";
import { logger } from "../utils/logger";

export class Bmobs {
  public BmobObject: any;
  protected log: any;
  public query: any;
  constructor () {
    Bmob.initialize(config.bmob.ApplicationId, config.bmob.RestApiKey, config.bmob.MasterKey);
    this.BmobObject = Bmob;
    this.log = logger;
  }

  public setTableName (tableName: string): void {
    this.query = Bmob.Query(tableName)
  }
  /**
   * 获取指定表的所有数据
   * @param tableName  表名称
   */
  protected QueryAll():Promise<any> {
    return new Promise((resolve, reject) => {
      this.query.find().then(res => {
        resolve(res)
      }).catch(err => {
        resolve(err);
        this.log.logSymbolsError(err.message)
      });
    });
  }

  /**
   * 查询一条数据
   * @param objectId 需要获取的数据id
   */
  protected QueryOne(objectId:string):Promise<any> {
    return new Promise((resolve, reject) => {
      this.query.get(objectId).then(res => {
        resolve(res)
      }).catch(err => {
        resolve(err);
        this.log.logSymbolsError(err.message)
      });
    });
  }

  /**
  * 删除一条数据
  * @param objectId 需要删除的数据id
  */
  protected DeleteOne(objectId:string): Promise<any> {
    return new Promise((resolve, reject) => {
      this.query.get(objectId).then(res => {
        res.unset('cover');
        res.save()
      }).catch(err => {
        this.log.logSymbolsError(err.message)
      })
    });
  }
  
  protected async AddArray(params:Object): Promise<any> {
    for (let item in params) {
      this.query.set(item,params[item])
    }
  
    return new Promise((resolve, reject) => {
      this.query.save().then(res => {
        resolve(res)
      }).catch(err => {
        this.log.logSymbolsError(err.message)
      })
    });
  }
} 